package com.cskaoyan.mall.realm;

import com.cskaoyan.mall.bean.Admin;
import com.cskaoyan.mall.bean.Permission;
import com.cskaoyan.mall.mapper.AdminMapper;
import com.cskaoyan.mall.mapper.PermissionMapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;

@Component
public class CustomRealm extends AuthorizingRealm {
    @Autowired
    AdminMapper adminMapper;
    @Autowired
    PermissionMapper permissionMapper;

    /**
     * 授权方法
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //getPrimaryPrincipal方法获取的是authenticationInfo中的principal参数信息
        String username = (String) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo authenticationInfo = new SimpleAuthorizationInfo();
        List<Admin> admins = adminMapper.selectAllByUsername(username);
        if(admins == null)
            return null;
        Admin admin = admins.get(0);
        Integer[] ids = admin.getRoleIds();
        if(ids.length == 0)
            return null;
        List<String> permissions = permissionMapper.selectPermissionsByRoleIds(ids);
        authenticationInfo.addStringPermissions(permissions);
        return authenticationInfo;
    }

    /**
     * 认证方法
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;
        String username = token.getUsername();
        List<String> strings = adminMapper.selectPasswordByUsername(username);
        String credential = strings.size() >= 1? strings.get(0) : null;
        System.out.println(credential);
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(username, credential, this.getName());
        return authenticationInfo;
    }
}
